package com.haiyou.dc.aggregate.linklist;

public class MyLinkList<E> extends MyAbstractList<E> {

    private Node first;

    static class Node<E> {

        E element;
        Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }

        @Override
        protected void finalize() throws Throwable {
            System.out.println("xxx" + next);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "element=" + element +
                    ", next=" + next +
                    '}';
        }
    }

    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }


    @Override
    public int add(E element) {
        return add(size, element);
    }

    @Override
    public int add(int index, E element) {
//        rangeCheckForAdd(index);
        if (index == 0) {
            first = new Node<>(element, first);
        } else {
            Node<E> prev = node(index - 1);
            prev.next = new Node<>(element, prev.next);
        }
        size++;
        return 0;
    }

    @Override
    public E set(int index, E element) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = element;
        return old;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public void remove(int index) {
        if (index == 0) {
            first = first.next;
        } else {
            Node<E> prev = node(index - 1);
            prev.next = prev.next.next;
        }
        size--;
    }


    @Override
    public int indexOf(E element) {
        return 0;
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public String toString() {

        Node<E> node = first;
        StringBuilder sb = new StringBuilder();
        while (node != null) {
            sb.append(node.element).append(",");
            node = node.next;
        }


        return sb.toString();
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("xxxxxxxx+xx");
    }
}
